/*
* @Date: 2020/4/14
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
/*
* @Date: 2020/1/8
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';

export default class extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount () {
    const parentNode = this.myRef.current.parentNode;
    parentNode.style.display = 'flex';
    parentNode.style.flexDirection = 'row';
    document.addEventListener('mouseup', this.onMouseUp);
    document.addEventListener('mousemove', this.onMouseMove);
  }

  componentWillUnmount () {
    document.removeEventListener('mouseup', this.onMouseUp);
    document.removeEventListener('mousemove', this.onMouseMove);
  }

  onMonseDown = (e) => {
    this.isSelected = true;
    this.curX = e.pageX;
    this.curY = e.pageY;
  }

  onMouseMove = (e) => {
    if (this.isSelected) {
      let prevElement = this.myRef.current.previousSibling;
      let nextElement = this.myRef.current.nextSibling;
      const prevClient = prevElement.getBoundingClientRect();
      const nextClient = nextElement.getBoundingClientRect();
      const pageX = e.pageX;
      const diff = this.curX - pageX;
      if ((prevClient.width - diff) < 20 || (nextClient.width + diff) < 20) {
        return;
      }
      prevElement.style.width = (prevClient.width - diff) + 'px';
      nextElement.style.width = (nextClient.width + diff) + 'px';
      this.curX = pageX;
    }
  }

  onMouseUp = (e) => {
    this.isSelected = false;
  }

  render() {
    const { className = '', style = {} } = this.props;
    return (
      <div
        onMouseDown={this.onMonseDown}
        className={className}
        style={{ cursor: 'w-resize', ...style, background: '#565656', height: '100%' }}
        ref={this.myRef}
      />
    );
  }
}
